package org.lanqiao.taru.lanqiao_demo.controller;

import org.lanqiao.taru.lanqiao_demo.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.lanqiao.taru.lanqiao_demo.vo.TempFileVo;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
    @Value("${my.uploadPath}")
    private String uploadFilePath;


    /**
     * 列出当前系统的盘符和根目录
     */
    @GetMapping("/root")
    public Result listRoot() {
        File[] files = File.listRoots();
        return Result.success("查询盘符成功", files);

    }

    /**
     * 根据具体的path，查询当前path有哪些文件
     */
    @PostMapping("/list")
    public Result listFile(@RequestBody TempFileVo tempFileVo) {
        File file = new File(tempFileVo.getPath());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            return Result.success("查询文件成功", files);
        } else {
            return Result.success("不能再执行", null);
        }
    }

    /**
     * 上传文件
     * @param myFile
     * @return
     */
    @PostMapping("/upload")
    public Result commonUploadFile(MultipartFile myFile) {
        if(myFile.isEmpty()){
            throw new RuntimeException("文件为空");

        }
        String newName = System.currentTimeMillis()+"_"+myFile.getOriginalFilename();
        try {
            File file = new File(uploadFilePath);
            if(!file.exists()){
                file.mkdir();
            }
            myFile.transferTo(new File(uploadFilePath+newName));
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败");

        }
        return Result.success("上传文件成功", newName);
    }
}